package com.md.util;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.PictureData;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Shape;
import org.apache.poi.xssf.usermodel.XSSFAnchor;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFPicture;
import org.apache.poi.xssf.usermodel.XSSFPictureData;
import org.apache.poi.xssf.usermodel.XSSFShape;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.Function;

/**
 * @author 刘骄阳
 * 2024-10-18 15:25
 */
public class ReadExcelImages {

  public static void main(String[] args) {
    String excelFilePath = "D://TK bottle 阻隔性测试报告 Lab trial report.xlsx";
    try (FileInputStream fis = new FileInputStream(excelFilePath);
         XSSFWorkbook workbook = new XSSFWorkbook(fis)) {

      // 获取工作表
      XSSFSheet sheet = workbook.getSheetAt(0);
      getXlsxPictures(sheet);
      // 获取工作表中的绘图对象
      XSSFDrawing drawing = sheet.createDrawingPatriarch();

      for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
        Row row = sheet.getRow(rowIndex);
        if (row != null) {
          // 遍历每一列
          for (int colIndex = 0; colIndex < row.getLastCellNum(); colIndex++) {
            Cell cell = row.getCell(colIndex);
            if (cell != null) {
              // 检查单元格是否包含图片


              Map<String, XSSFShape> map =
                CollectionUtil.toMap(drawing.getShapes(), Shape::getShapeName, Function.identity());
              System.out.println();
              for (XSSFShape shape : drawing.getShapes()) {
                XSSFAnchor anchor = shape.getAnchor();
                // 检查锚点的行和列
                if (anchor instanceof XSSFClientAnchor) {
                  XSSFClientAnchor clientAnchor = (XSSFClientAnchor) anchor;
                  int row1 = clientAnchor.getRow1();
                  int col1 = clientAnchor.getCol1();
                  // 检查当前单元格是否包含该图片
                  if (row1 == rowIndex && col1 == colIndex) {
                    System.out.println("Found image in Row: " + rowIndex + ", Column: " + colIndex);
                    System.out.println("Image anchor positions: dx1=" + clientAnchor.getDx1() +
                      ", dx2=" + clientAnchor.getDx2() +
                      ", dy1=" + clientAnchor.getDy1() +
                      ", dy2=" + clientAnchor.getDy2());
                  }
                }
              }
            }
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static Map<String, PictureData> getXlsxPictures(final XSSFSheet sheet) throws IOException {
    Map<String, PictureData> map = new HashMap<String, PictureData>();
    for (XSSFShape shape : sheet.getDrawingPatriarch().getShapes()) {
      XSSFClientAnchor anchor = (XSSFClientAnchor) shape.getAnchor();
      if (shape instanceof XSSFPicture) {
        XSSFPicture pic = (XSSFPicture) shape;
        //获取行编号
        int row = anchor.getRow2();
        //获取列编号
        int col = anchor.getCol2();
        map.put(row + "-" + col, pic.getPictureData());
      }
    }
    return map;
  }

  public static void create() {
    // 图像的宽度和高度
    int width = 800;
    int height = 600;

    // 创建一个 BufferedImage 对象
    BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    // 获取 Graphics 对象
    Graphics2D g2d = bufferedImage.createGraphics();

    // 绘制背景
    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, width, height);

    // 绘制图表示例（矩形）
    g2d.setColor(Color.BLUE);
    g2d.fillRect(100, 100, 600, 400);

    // 释放图形上下文
    g2d.dispose();

    // 保存为 PNG 文件
    File outputfile = new File("D:\\uploadFile\\扥莫\\" + UUID.randomUUID() + ".png");
    try {
      ImageIO.write(bufferedImage, "png", outputfile);
      System.out.println("图像已成功保存为 " + outputfile.getAbsolutePath());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void convertBase64ToFile(final byte[] decodedBytes, final File outputFile) {
    try (FileOutputStream fos = new FileOutputStream(outputFile)) {
      fos.write(decodedBytes);
      System.out.println("文件已成功创建: " + outputFile.getAbsolutePath());
    } catch (IOException e) {
      // 处理异常
      e.printStackTrace();
    }
  }

  public static void mai2(String[] args) {
    String excelFilePath = "D://TK bottle 阻隔性测试报告 Lab trial report.xlsx";

    try (FileInputStream fis = new FileInputStream(excelFilePath);
         XSSFWorkbook workbook = new XSSFWorkbook(fis)) {

      // 获取工作表
      XSSFSheet sheet = workbook.getSheetAt(0);

      // 获取所有图片数据
      List<XSSFPictureData> pictures = workbook.getAllPictures();

      // 获取工作表中的绘图对象
      XSSFDrawing drawing = sheet.createDrawingPatriarch();

      // 遍历每一行
      for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
        Row row = sheet.getRow(rowIndex);
        if (row != null) {
          // 遍历每一列
          for (int colIndex = 0; colIndex < row.getLastCellNum(); colIndex++) {
            Cell cell = row.getCell(colIndex);
            if (cell != null) {
              // 检查单元格是否包含图片
              List<XSSFShape> shapes = drawing.getShapes();
              shapes.forEach(xssfShape -> {
                XSSFAnchor anchor = xssfShape.getAnchor();
                System.out.println(anchor.getDx1());
                System.out.println(anchor.getDx2());
                System.out.println(anchor.getDy1());
                System.out.println(anchor.getDy2());
              });
            }
          }
        }
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  public static void main1(String[] args) {
    String excelFilePath = "path/to/your/excel/file.xlsx";
    String outputDir = "path/to/output/directory/";

    try (FileInputStream fis = new FileInputStream(excelFilePath);
         XSSFWorkbook workbook = new XSSFWorkbook(fis)) {

      List<XSSFPictureData> pictures = workbook.getAllPictures();
      for (XSSFPictureData picture : pictures) {
        String ext = picture.suggestFileExtension();
        byte[] bytes = picture.getData();

        // 生成文件名
        String fileName = outputDir + "image" + picture.getPackagePart().getPartName().getName().hashCode() + "." + ext;

        try (FileOutputStream fos = new FileOutputStream(fileName)) {
          fos.write(bytes);
        }
        System.out.println("Saved image: " + fileName);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
